package com.example.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

@Slf4j
public class FileUtil {
    public static int upload(MultipartFile file,StringBuilder newName,String path){
        String fileNames = file.getOriginalFilename();//这个fileNames是上传的文件名（不是地址）
        File savedFile;
        int split = fileNames.lastIndexOf(".");
        String suffix = fileNames.substring(split + 1, fileNames.length());//文件后缀，用于判断上传的文件是否是合法的
        //判断文件类型，因为我这边是图片，所以只设置三种合法格式
        try {
            if (suffix.equals("jpg") || suffix.equals("png") || suffix.equals("gif")) {
                //正确的类型，保存文件
                byte[] bytes = file.getBytes();
                newName.replace(0,newName.length(), new Date().getTime() + "." + suffix);
//                File savedFile = new File(paths+"/src/main/resources/static/images/"+newName);
                savedFile = new File(path + newName);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(savedFile));
                stream.write(bytes);
                stream.close();
            }else
                return 0;
        }catch (Exception e){
            log.error("FileUtil 工具类的 upload 方法出现异常:");
            e.printStackTrace();
            return -1;
        }
        log.info("图片上传完毕，存储地址为：" + savedFile.getAbsolutePath());
        return 1;
        }

        public static int delete(String imgName,String path){
        try {
            File oriImg = new File(path + imgName);
            log.info("删除原头像");
            oriImg.delete();
        }catch (Exception e){
            log.error("FileUtil 工具类的 delete 方法出现异常:");
            e.printStackTrace();
            return -1;
        }
        return 1;
        }

}
